package com.tchcn.supermarket.ui.fragment;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fanwe.library.adapter.http.model.SDResponse;
import com.tchcn.library.http.AppRequestCallback;
import com.tchcn.library.model.BaseActModel;
import com.tchcn.library.model.UserInfoModel;
import com.tchcn.library.utils.LogUtil;
import com.tchcn.supermarket.R;
import com.tchcn.supermarket.adapter.GoodsAdapter;
import com.tchcn.supermarket.adapter.GoodsTypeAdapter;
import com.tchcn.supermarket.base.BaseRecyclerAdapter;
import com.tchcn.supermarket.base.SBaseFragment;
import com.tchcn.supermarket.common.SCommonInterface;
import com.tchcn.supermarket.dao.PendingOrdersModelDao;
import com.tchcn.supermarket.dbmodel.PendingOrderModel;
import com.tchcn.supermarket.dialog.CancelPaymentDialog;
import com.tchcn.supermarket.dialog.DiscountInputDialog;
import com.tchcn.supermarket.dialog.GoodNumInputDialog;
import com.tchcn.supermarket.dialog.ManuallyWipeZeroDialog;
import com.tchcn.supermarket.dialog.PendingOrderDialog;
import com.tchcn.supermarket.listener.AddGoodListener;
import com.tchcn.supermarket.model.Good;
import com.tchcn.supermarket.model.GoodInfoActModel;
import com.tchcn.supermarket.model.GoodTypeActModel;
import com.tchcn.supermarket.model.NoCodeGoodActModel;
import com.tchcn.supermarket.model.PayResultsModel;
import com.tchcn.supermarket.ui.activity.CashierHomeActivity;
import com.tchcn.supermarket.utils.AnimationUtil;
import com.tchcn.supermarket.utils.FormatUtil;
import com.tchcn.supermarket.utils.KeyboardUtil;
import com.tchcn.supermarket.utils.SDToast;
import com.tchcn.supermarket.utils.TimeUtils;
import com.tchcn.supermarket.utils.ViewBinder;
import com.tchcn.supermarket.view.MyRecyclerView;

import java.util.ArrayList;
import java.util.List;

/**
 *  收银台
 * Created by humu on 2018/4/29.
 */

public class CashierHomeFragment extends SBaseFragment implements AddGoodListener {

    //已选商品列表
    private MyRecyclerView rv_goods;
    //删除单品
    private RelativeLayout rl_del_good;
    //选择物品类型列表
    private RecyclerView rv_types;
    //商品数量
    private TextView tv_good_num;
    //清空
    private Button btn_clear_goods;
    //价格
    private TextView tv_money;
    //挂单
    private RelativeLayout rl_pending_order;
    //当前挂单数量
    private TextView tv_pending_order_num;
    //左侧收银台
    private LinearLayout ll_left_cashier;
    //左侧会员/优惠信息
    private LinearLayout ll_left_member;
    //右侧添加商品
    private LinearLayout ll_right_operate;
    //右侧支付
    private LinearLayout ll_right_pay;
    //结算
    private Button btn_clearing;
    //取消
    private TextView tv_cancel_pay;
    //单品折扣
    private RelativeLayout rl_single_item_discount;
    //手动抹零
    private RelativeLayout rl_wipe_zero;
    private TextView tv_wipe_zero;
    //整单折扣
    private RelativeLayout rl_entire_discount;
    private TextView tv_entire_discount;
    private TextView tv_offermoney;
    private TextView tv_should_take_left;
    private TextView tv_wipe_zero_num;
    private TextView tv_whole_discount;
    private TextView tv_should_take_right;
    private TextView tv_actual_take;
    private RelativeLayout rl_cash;
    private RelativeLayout rl_wechat;
    private RelativeLayout rl_alipay;
    private RelativeLayout rl_yue;
    private RelativeLayout rl_bank_card;
    private TextView tv_change;
    private LinearLayout ll_pay_results;
    private EditText et_good_code;
    private Button btn_search_good_by_code;
    private TextView tv_pre_money; //惠前金额

    private static CashierHomeFragment fragment;
    private int last_good_position = -1;
    private int last_type_position = 0;
    private GoodsTypeAdapter typeAdapter;
    private List<Good> goodList = new ArrayList<>();
    private GoodsAdapter adapter;
    private float allMoney = 0.0f; //总价格,不考虑任何优惠
    private float realMoney = 0.0f; //真实价格(不包含单品打折的总优惠)
    private float offerMoney = 0.0f; //已优惠价格
    private float wholeDiscount = 0.0f; //整单折扣
    private float wipedMoney = 0.0f; //抹去零头
    private float mustPayMoney = 0.0f; //抹去零头和整单折扣之后的价格,不变
    private float payMoney = 0.0f; //该支付价格,随着部分付款会随之变化
    private GoodsListFragment goodsListFragment;
    private int payType = -1; //支付方式
    private PayResultsAdapter payResultsAdapter;

    public static CashierHomeFragment getInstance(){
        if(fragment == null){
            fragment = new CashierHomeFragment();
        }
        return fragment;
    }

    @Override
    protected int onCreateContentView() {
        return R.layout.sfragment_cashier_home;
    }

    @Override
    protected void initView() {
        activity.registerMyTouchListener(myTouchListener);
        initUI();
        initTypeList();
        initPendingOrders();
    }

    private CashierHomeActivity.MyTouchListener myTouchListener = new CashierHomeActivity.MyTouchListener() {
        @Override
        public boolean onTouchEvent(MotionEvent event) {
            KeyboardUtil.hideSoftInput(activity);
            return true;
        }
    };

    private void initUI() {
        rv_goods = find(R.id.rv_goods);
        rv_types = find(R.id.rv_types);
        rl_del_good = find(R.id.rl_del_good);
        rl_del_good.setOnClickListener(this);
        tv_good_num = find(R.id.tv_good_num);
        btn_clear_goods = find(R.id.btn_clear_goods);
        btn_clear_goods.setOnClickListener(this);
        tv_money = find(R.id.tv_money);
        rl_pending_order = find(R.id.rl_pending_order);
        rl_pending_order.setOnClickListener(this);
        tv_pending_order_num = find(R.id.tv_pending_order_num);
        ll_left_cashier = find(R.id.ll_left_cashier);
        ll_left_member = find(R.id.ll_left_member);
        ll_right_operate = find(R.id.ll_right_operate);
        ll_right_pay = find(R.id.ll_right_pay);
        btn_clearing = find(R.id.btn_clearing);
        btn_clearing.setOnClickListener(this);
        tv_cancel_pay = find(R.id.tv_cancel_pay);
        tv_cancel_pay.setOnClickListener(this);
        rl_single_item_discount = find(R.id.rl_single_item_discount);
        rl_single_item_discount.setOnClickListener(this);
        rl_wipe_zero = find(R.id.rl_wipe_zero);
        tv_wipe_zero = find(R.id.tv_wipe_zero);
        rl_entire_discount = find(R.id.rl_entire_discount);
        tv_entire_discount = find(R.id.tv_entire_discount);
        rl_wipe_zero.setOnClickListener(this);
        rl_entire_discount.setOnClickListener(this);
        tv_offermoney = find(R.id.tv_offermoney);
        tv_should_take_left = find(R.id.tv_should_take_left);
        tv_wipe_zero_num = find(R.id.tv_wipe_zero_num);
        tv_whole_discount = find(R.id.tv_whole_discount);
        tv_should_take_right = find(R.id.tv_should_take_right);
        tv_actual_take = find(R.id.tv_actual_take);
        rl_cash = find(R.id.rl_cash);
        rl_cash.setOnClickListener(this);
        rl_wechat = find(R.id.rl_wechat);
        rl_wechat.setOnClickListener(this);
        rl_alipay = find(R.id.rl_alipay);
        rl_alipay.setOnClickListener(this);
        rl_yue = find(R.id.rl_yue);
        rl_yue.setOnClickListener(this);
        rl_bank_card = find(R.id.rl_bank_card);
        rl_bank_card.setOnClickListener(this);
        tv_change = find(R.id.tv_change);
        TextView tv_clear_actual = find(R.id.tv_clear_actual);
        tv_clear_actual.setOnClickListener(this);
        TextView tv_point = find(R.id.tv_point);
        tv_point.setOnClickListener(this);
        TextView tv_0 = find(R.id.tv_0);
        tv_0.setOnClickListener(this);
        TextView tv_00 = find(R.id.tv_00);
        tv_00.setOnClickListener(this);
        TextView tv_1 = find(R.id.tv_1);
        tv_1.setOnClickListener(this);
        TextView tv_2 = find(R.id.tv_2);
        tv_2.setOnClickListener(this);
        TextView tv_3 = find(R.id.tv_3);
        tv_3.setOnClickListener(this);
        TextView tv_4 = find(R.id.tv_4);
        tv_4.setOnClickListener(this);
        TextView tv_5 = find(R.id.tv_5);
        tv_5.setOnClickListener(this);
        TextView tv_6 = find(R.id.tv_6);
        tv_6.setOnClickListener(this);
        TextView tv_7 = find(R.id.tv_7);
        tv_7.setOnClickListener(this);
        TextView tv_8 = find(R.id.tv_8);
        tv_8.setOnClickListener(this);
        TextView tv_9 = find(R.id.tv_9);
        tv_9.setOnClickListener(this);
        TextView tv_10 = find(R.id.tv_10);
        tv_10.setOnClickListener(this);
        TextView tv_20 = find(R.id.tv_20);
        tv_20.setOnClickListener(this);
        TextView tv_50 = find(R.id.tv_50);
        tv_50.setOnClickListener(this);
        TextView tv_100 = find(R.id.tv_100);
        tv_100.setOnClickListener(this);
        RelativeLayout rl_del = find(R.id.rl_del);
        rl_del.setOnClickListener(this);
        TextView tv_confirm_order = find(R.id.tv_confirm_order);
        tv_confirm_order.setOnClickListener(this);
        ll_pay_results = find(R.id.ll_pay_results);
        et_good_code = find(R.id.et_good_code);
        btn_search_good_by_code = find(R.id.btn_search_good_by_code);
        btn_search_good_by_code.setOnClickListener(this);
        TextView tv_return = find(R.id.tv_return);
        tv_return.setOnClickListener(this);
        tv_pre_money = find(R.id.tv_pre_money);

        LinearLayoutManager typeLayoutManager = new LinearLayoutManager(context);
        typeLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_types.setLayoutManager(typeLayoutManager);

        rv_goods.setIsRefreshEnabled(false);
        rv_goods.setIsLoadMoreEnabled(false);
        adapter = new GoodsAdapter(this);
        rv_goods.setOnItemClickListener(new BaseRecyclerAdapter.OnItemClickListener<Good>() {
            @Override
            public void onItemClick(View covertView, int position, Good data) {
                if(position != last_good_position){
                    if(last_good_position >= 0){
                        adapter.getItem(last_good_position).setIs_checked(false);
                    }
                    data.setIs_checked(true);
                    last_good_position = position;
                    adapter.notifyDataSetChanged();
                }
            }
        });
        rv_goods.setAdapter(adapter);

        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        goodsListFragment = GoodsListFragment.getInstance();
        goodsListFragment.setAddGoodListener(this);
        ft.add(R.id.frame_goods, goodsListFragment).commit();
        typeAdapter = new GoodsTypeAdapter();
        typeAdapter.setOnItemClickListener(new GoodsTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int id, int position) {
                int view_id = view.getId();
                if(view_id == R.id.rl_main){
                    if(position != last_type_position){
                        if(last_type_position >= 0){
                            typeAdapter.getItem(last_type_position).setChecked(false);
                            typeAdapter.notifyItemChanged(last_type_position);
                        }
                        typeAdapter.getItem(position).setChecked(true);
                        last_type_position = position;
                        typeAdapter.notifyItemChanged(last_type_position);
                        typeRvScrollToCenter(position);
                        goodsListFragment.setDeal_id(typeAdapter.getItem(last_type_position).getId());
                    }
                }
            }
        });
        rv_types.setAdapter(typeAdapter);

        tv_actual_take.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String actualTakeStr = s.toString();
                if(FormatUtil.isFloat(actualTakeStr)){
                    Float actualTake = Float.parseFloat(actualTakeStr);
                    if(actualTake >= payMoney){
                        ViewBinder.setTextView(tv_change,(actualTake - payMoney)+"");
                    }else{
                        ViewBinder.setTextView(tv_change,"0");
                    }
                }else{
                    ViewBinder.setTextView(tv_change,"0");
                }
            }
        });

        tv_should_take_right.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String actualTakeStr = tv_actual_take.getText().toString();
                if(FormatUtil.isFloat(actualTakeStr)){
                    Float actualTake = Float.parseFloat(actualTakeStr);
                    if(actualTake >= payMoney){
                        ViewBinder.setTextView(tv_change,(actualTake - payMoney)+"");
                    }else{
                        ViewBinder.setTextView(tv_change,"0");
                    }
                }else{
                    ViewBinder.setTextView(tv_change,"0");
                }
            }
        });

        RecyclerView rv_pay_results = find(R.id.rv_pay_results);
        rv_pay_results.setLayoutManager(new LinearLayoutManager(context));
        rv_pay_results.setNestedScrollingEnabled(false);
        payResultsAdapter = new PayResultsAdapter();
        rv_pay_results.setAdapter(payResultsAdapter);

    }

    //挂单初始化
    private void initPendingOrders() {
        PendingOrderModel pendingOrderModel = PendingOrdersModelDao.queryModel();
        if(pendingOrderModel != null){
            List<PendingOrderModel.PendingOrder> pendingOrderList = pendingOrderModel.getOrder_list();
            if(pendingOrderList.size() > 0){
                tv_pending_order_num.setVisibility(View.VISIBLE);
                tv_pending_order_num.setText(pendingOrderList.size()+"");
            }else{
                tv_pending_order_num.setVisibility(View.GONE);
                tv_pending_order_num.setText("0");
            }
        }else{
            tv_pending_order_num.setVisibility(View.GONE);
        }
    }

    public void refreshPendingOrders(){
        initPendingOrders();
    }

    public void getPendingOrderRefresh(PendingOrderModel.PendingOrder pendingOrder){
        last_good_position = -1;
        goodList = pendingOrder.getGood_list();
        adapter.setDatas(goodList);
        refreshMoneyAndNum();
    }

    //右侧头部商品类型列表
    public void initTypeList() {
        if(typeAdapter.getItemCount() <= 0){
            SCommonInterface.getAllTables(activity.getLocationId(), new AppRequestCallback<GoodTypeActModel>() {
                @Override
                protected void onSuccess(SDResponse sdResponse) {
                    LogUtil.e("getAllTables",sdResponse.getResult());
                    if(actModel.isOk()){
                        GoodTypeActModel.GoodTypeData data = actModel.getData();
                        if(data != null){
                            List<GoodTypeActModel.GoodTypeData.GoodType> goodTypeList = data.getRes();
                            if(goodTypeList != null && goodTypeList.size() > 0){
                                goodTypeList.get(0).setChecked(true);
                                typeAdapter.setDatas(goodTypeList);
                                goodsListFragment.setDeal_id(typeAdapter.getItem(0).getId());
                            }else{
                                typeAdapter.setDatas(new ArrayList<GoodTypeActModel.GoodTypeData.GoodType>());
                            }
                        }else{
                            typeAdapter.setDatas(new ArrayList<GoodTypeActModel.GoodTypeData.GoodType>());
                        }
                    }else{
                        typeAdapter.setDatas(new ArrayList<GoodTypeActModel.GoodTypeData.GoodType>());
                    }
                }
            });
        }
    }

    //类型点击时滚动到中间
    private void typeRvScrollToCenter(int position){
        //得到布局
        LinearLayoutManager layoutManager = (LinearLayoutManager) rv_types.getLayoutManager();

        //得到屏幕可见的item的总数
        int childCount = layoutManager.getChildCount();
        int middlechild = 0;
        if (childCount != typeAdapter.getItemCount()) {
            //可见item的总数除以2  就可以拿到中间位置
            middlechild = childCount / 2;
        }
        //判断你点的是中间位置的上面还是中间的下面位置
        //RecyclerView必须加 && position != 2,listview不需要
        if (position <= (layoutManager.findFirstVisibleItemPosition() + middlechild) && position != 2) {
            int willposition = position + 1 - middlechild;
            if(willposition >= 0){
                rv_types.smoothScrollToPosition(willposition);
            }
        } else {
            int willposition = position - 1 + middlechild;
            if(willposition >= 0){
                rv_types.smoothScrollToPosition(willposition);
            }
        }
    }

    //右侧商品点击
    @Override
    public void addGood(Float addNum,NoCodeGoodActModel.NoCodeGoodData.NoCodeGoodModel model) {
        if(last_good_position >= 0){
            if(last_good_position < adapter.getItemCount()){
                adapter.getItem(last_good_position).setIs_checked(false);
            }
        }
        if(isHasGood(model.getId())){
            for(int i = 0;i<goodList.size();i++){
                Good good = goodList.get(i);
                if(good.getId().equals(model.getId())){
                    good.setNum(good.getNum() + addNum);
                    good.setIs_checked(true);
                    adapter.setDatas(goodList);
                    refreshMoneyAndNum();
                    break;
                }
            }
        }else{
            Good good = new Good();
            good.setId(model.getId());
            good.setName(model.getCate_name());
            good.setUnit(model.getUnit());
            good.setMoney(Float.parseFloat(model.getRetail_price()));
            good.setIs_checked(true);
            good.setNum(addNum);
            goodList.add(good);
            last_good_position = goodList.size() - 1;
            adapter.setDatas(goodList);
            rv_goods.scrollToBottom();
            refreshMoneyAndNum();
        }
    }

    //根据条形码搜索
    public void addGood(Float addNum,GoodInfoActModel.GoodInfoByIdData.GoodInfoById model) {
        if(last_good_position >= 0){
            if(last_good_position < adapter.getItemCount()){
                adapter.getItem(last_good_position).setIs_checked(false);
            }
        }
        if(isHasGood(model.getId())){
            for(int i = 0;i<goodList.size();i++){
                Good good = goodList.get(i);
                if(good.getId().equals(model.getId())){
                    good.setNum(good.getNum() + addNum);
                    good.setIs_checked(true);
                    adapter.setDatas(goodList);
                    refreshMoneyAndNum();
                    break;
                }
            }
        }else{
            Good good = new Good();
            good.setId(model.getId());
            good.setName(model.getCate_name());
            good.setUnit(model.getUnit());
            good.setMoney(Float.parseFloat(model.getRetail_price()));
            good.setIs_checked(true);
            good.setNum(addNum);
            goodList.add(good);
            last_good_position = goodList.size() - 1;
            adapter.setDatas(goodList);
            rv_goods.scrollToBottom();
            refreshMoneyAndNum();
        }
    }

    //判断左侧列表是否存在点击的商品
    private boolean isHasGood(String goodId){
        for(int i = 0;i<goodList.size();i++){
            Good g = goodList.get(i);
            if(g.getId().equals(goodId)){
                last_good_position = i;
                adapter.notifyDataSetChanged();
                rv_goods.scrollToPosition(last_good_position);
                return true;
            }
        }
        return false;
    }

    /**
     * 更新价格和商品数量信息
     */
    public void refreshMoneyAndNum(){
        allMoney = 0.0f;
        offerMoney = 0.0f;
        realMoney = 0.0f;
        int goodNum = 0;
        if(goodList != null && goodList.size() > 0){
            goodNum = goodList.size();
            for(Good good : goodList){
                allMoney += good.getNum() * good.getMoney();
                if(good.getDiscount() > 0){
                    realMoney += good.getNum() * (good.getMoney() * good.getDiscount());
                }else{
                    realMoney += good.getNum() * good.getMoney();
                }
                if(good.getDiscount() > 0){
                    offerMoney += good.getNum() * good.getMoney() - good.getNum() * (good.getMoney() * good.getDiscount());
                }
            }
            tv_good_num.setText("共"+goodList.size()+"个商品");
        }
        ViewBinder.setTextView(tv_money,"¥"+realMoney);
        ViewBinder.setTextView(tv_offermoney,"已优惠"+offerMoney+"元");
        ViewBinder.setTextView(tv_good_num,"共"+goodNum+"个商品");
    }

    private void initOrderInfo(){
        payMoney = realMoney;
        mustPayMoney = realMoney;
        ViewBinder.setTextView(tv_should_take_left,"¥"+realMoney);
        ViewBinder.setTextView(tv_should_take_right,"¥"+realMoney);
        //ViewBinder.setTextView(tv_actual_take,realMoney+ b
        ViewBinder.setTextView(tv_actual_take,realMoney+"");
        ViewBinder.setTextView(tv_pre_money,"惠前金额：¥"+realMoney);
    }

    private void payTypeChange(){
        rl_cash.setBackgroundColor(getResources().getColor(R.color.white));
        rl_wechat.setBackgroundColor(getResources().getColor(R.color.white));
        rl_alipay.setBackgroundColor(getResources().getColor(R.color.white));
        rl_yue.setBackgroundColor(getResources().getColor(R.color.white));
        rl_bank_card.setBackgroundColor(getResources().getColor(R.color.white));
        switch (payType){
            case 1:
                rl_cash.setBackgroundResource(R.drawable.sshape_checked_good_bg);
                break;
            case 2:
                rl_wechat.setBackgroundResource(R.drawable.sshape_checked_good_bg);
                break;
            case 3:
                rl_alipay.setBackgroundResource(R.drawable.sshape_checked_good_bg);
                break;
            case 4:
                rl_yue.setBackgroundResource(R.drawable.sshape_checked_good_bg);
                break;
            case 5:
                rl_bank_card.setBackgroundResource(R.drawable.sshape_checked_good_bg);
                break;
        }
    }

    class PayResultsAdapter extends BaseRecyclerAdapter<PayResultsModel>{

        @Override
        public int getItemLayoutId(int viewType) {
            return R.layout.sitem_pay_results;
        }

        @Override
        public void setUpData(CommonHolder holder, int position, int viewType, PayResultsModel data) {
            TextView tv_index = getView(holder,R.id.tv_index);
            TextView tv_pay_type = getView(holder,R.id.tv_pay_type);
            TextView tv_pay_money = getView(holder,R.id.tv_pay_money);
            if((position+1) < 10){
                ViewBinder.setTextView(tv_index,"0"+(position+1));
            }else{
                ViewBinder.setTextView(tv_index,(position+1)+"");
            }
            ViewBinder.setTextView(tv_pay_type,data.getPayType());
            ViewBinder.setTextView(tv_pay_money,"¥"+data.getPayMoney());

        }
    }

    private void finishPay(){
        ll_left_cashier.setVisibility(View.VISIBLE);
        ll_right_operate.setVisibility(View.VISIBLE);
        ll_left_member.setAnimation(AnimationUtil.getCashierHiddenAnim());
        ll_right_pay.setAnimation(AnimationUtil.getCashierHiddenAnim());
        ll_left_member.setVisibility(View.GONE);
        ll_right_pay.setVisibility(View.GONE);

        ll_pay_results.setVisibility(View.GONE);
        payResultsAdapter.setDatas(new ArrayList<PayResultsModel>());
        ViewBinder.setTextView(tv_actual_take,"");
        payType = -1;
        rl_cash.setBackgroundColor(getResources().getColor(R.color.white));
        rl_wechat.setBackgroundColor(getResources().getColor(R.color.white));
        rl_alipay.setBackgroundColor(getResources().getColor(R.color.white));
        rl_yue.setBackgroundColor(getResources().getColor(R.color.white));
        rl_bank_card.setBackgroundColor(getResources().getColor(R.color.white));
        ViewBinder.setTextView(tv_wipe_zero,"");
        ViewBinder.setTextView(tv_wipe_zero_num,"暂无");
        ViewBinder.setTextView(tv_entire_discount,"");
        ViewBinder.setTextView(tv_whole_discount,"暂无");
        wipedMoney = 0.0f;
        wholeDiscount = 0.0f;
    }

    public boolean isInShopcart(String goodId){
        List<Good> goodList = adapter.getDatas();
        if(goodList != null && goodList.size() > 0){
            for(Good good : goodList){
                if(goodId.equals(good.getId())){
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if(id == R.id.rl_del_good){ //单品删除
            if(!goodList.isEmpty()){
                if(last_good_position >= 0 && goodList.size() > last_good_position){
                    goodList.remove(last_good_position);
                    if(goodList.size() > 0){
                        last_good_position = goodList.size() - 1;
                        goodList.get(goodList.size() - 1).setIs_checked(true);
                        adapter.setDatas(goodList);
                        adapter.notifyItemChanged(last_good_position);
                    }else{
                        last_good_position = -1;
                        adapter.setDatas(goodList);
                    }
                    refreshMoneyAndNum();
                }else{
                    SDToast.showToast(context,"未选中商品");
                }
            }else{
                SDToast.showToast(context,"商品列表为空");
            }
        }else if(id == R.id.btn_clear_goods){ //清空
            if(!goodList.isEmpty()){
                goodList.clear();
                adapter.setDatas(goodList);
                refreshMoneyAndNum();
            }
        }else if(id == R.id.rl_pending_order){ //挂单
            if(goodList.isEmpty()){ //打开挂单列表
                //打开挂单列表
                PendingOrderModel model = PendingOrdersModelDao.queryModel();
                if(model != null){
                    List<PendingOrderModel.PendingOrder> pendingOrderList = model.getOrder_list();
                    if(pendingOrderList != null && pendingOrderList.size() > 0){
                        PendingOrderDialog.newInstance()
                                .setOutCancel(true)
                                .show(getChildFragmentManager());
                        KeyboardUtil.hideSoftInput(activity);
                    }else{
                        SDToast.showToast(context,"无挂单");
                    }
                }else{
                    SDToast.showToast(context,"无挂单");
                }
            }else{ //当前订单挂单
                PendingOrderModel model = PendingOrdersModelDao.queryModel();
                if(model != null){
                    PendingOrderModel.PendingOrder pendingOrder = new PendingOrderModel.PendingOrder();
                    for(Good good : goodList){
                        good.setIs_checked(false);
                    }
                    pendingOrder.setGood_list(goodList);
                    pendingOrder.setGood_num(goodList.size());
                    pendingOrder.setMoney(allMoney);
                    pendingOrder.setReal_money(realMoney);
                    pendingOrder.setPend_time(TimeUtils.getTimeString());
                    pendingOrder.setOffer_money(offerMoney);
                    model.getOrder_list().add(pendingOrder);
                    PendingOrdersModelDao.insertModel(model);
                }else{
                    PendingOrderModel pendingOrderModel = new PendingOrderModel();
                    List<PendingOrderModel.PendingOrder> pendingOrderList = new ArrayList<>();
                    PendingOrderModel.PendingOrder pendingOrder = new PendingOrderModel.PendingOrder();
                    for(Good good : goodList){
                        good.setIs_checked(false);
                    }
                    pendingOrder.setGood_list(goodList);
                    pendingOrder.setGood_num(goodList.size());
                    pendingOrder.setMoney(allMoney);
                    pendingOrder.setReal_money(realMoney);
                    pendingOrder.setOffer_money(offerMoney);
                    pendingOrder.setPend_time(TimeUtils.getTimeString());
                    pendingOrderList.add(pendingOrder);
                    pendingOrderModel.setOrder_list(pendingOrderList);
                    PendingOrdersModelDao.insertModel(pendingOrderModel);
                }
                last_good_position = -1;
                goodList.clear();
                adapter.setDatas(goodList);
                rv_goods.setAdapter(adapter);
                refreshMoneyAndNum();
                initPendingOrders();
            }
        }else if(id == R.id.btn_clearing){ //结算

            if(goodList.size() > 0){
                ll_left_member.setAnimation(AnimationUtil.getCashierShowAnim());
                ll_right_pay.setAnimation(AnimationUtil.getCashierShowAnim());
                ll_left_member.setVisibility(View.VISIBLE);
                ll_right_pay.setVisibility(View.VISIBLE);
                ll_left_cashier.setVisibility(View.GONE);
                ll_right_operate.setVisibility(View.GONE);
                initOrderInfo();
            }else{
                SDToast.showToast(context,"无商品可结算");
            }

        }else if(id == R.id.tv_cancel_pay){ //取消
            if(ll_pay_results.getVisibility() == View.GONE){
                finishPay();
            }else{
                if(payMoney > 0){
                    CancelPaymentDialog.newInstance(new CancelPaymentDialog.SetOnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            SDToast.showToast(context,"取消支付");
                            finishPay();
                        }
                    }).setOutCancel(true).show(getChildFragmentManager());
                    KeyboardUtil.hideSoftInput(activity);
                }else{
                    SDToast.showToast(context,"订单已支付完成");
                    finishPay();
                }
            }
        }else if(id == R.id.rl_single_item_discount){ //单品折扣
            if(last_good_position >= 0 && goodList.size() > last_good_position){
                final Good good = goodList.get(last_good_position);
                float goodNum = good.getNum();
                DiscountInputDialog.newInstance("单品折扣",good.getMoney()*goodNum,new DiscountInputDialog.SetOnConfirmListener() {
                    @Override
                    public void onConfirm(float discount,String discount_result) {
                        good.setDiscount(discount);
                        adapter.notifyItemChanged(last_good_position);
                        refreshMoneyAndNum();
                    }

                    @Override
                    public void onReset() {
                        good.setDiscount(1);
                        adapter.notifyItemChanged(last_good_position);
                        refreshMoneyAndNum();
                    }

                }).setOutCancel(true)
                        .show(getChildFragmentManager());
                KeyboardUtil.hideSoftInput(activity);
            }else{
                SDToast.showToast(context,"未选中商品");
            }
        }else if(id == R.id.rl_entire_discount){ //整单折扣
            if(ll_pay_results.getVisibility() == View.GONE){
                if(wipedMoney == 0 || (wholeDiscount > 0 && wholeDiscount < 1)){
                    DiscountInputDialog.newInstance("整单折扣",realMoney, new DiscountInputDialog.SetOnConfirmListener() {
                        @Override
                        public void onConfirm(float discount,String discount_result) {
                            wipedMoney = 0;
                            ViewBinder.setTextView(tv_wipe_zero,"");
                            ViewBinder.setTextView(tv_wipe_zero_num,"暂无");
                            if(discount > 0 && discount < 1){
                                float currentMoney = realMoney - wipedMoney;
                                wholeDiscount = discount;
                                //finalMoney = Float.parseFloat(discount_result);
                                ViewBinder.setTextView(tv_entire_discount,(discount*100)+"折");
                                ViewBinder.setTextView(tv_whole_discount,(discount*100)+"折");
                                payMoney = currentMoney * wholeDiscount;
                                mustPayMoney = currentMoney * wholeDiscount;
                                ViewBinder.setTextView(tv_should_take_left,"¥"+(currentMoney * wholeDiscount));
                                ViewBinder.setTextView(tv_should_take_right,"¥"+(currentMoney * wholeDiscount));
                            }else{
                                SDToast.showToast(context,"无折扣");
                                float currentMoney = realMoney - wipedMoney;
                                wholeDiscount = 1;
                                ViewBinder.setTextView(tv_entire_discount,"");
                                ViewBinder.setTextView(tv_whole_discount,"暂无");
                                payMoney = currentMoney * wholeDiscount;
                                mustPayMoney = currentMoney * wholeDiscount;
                                ViewBinder.setTextView(tv_should_take_left,"¥"+(currentMoney * wholeDiscount));
                                ViewBinder.setTextView(tv_should_take_right,"¥"+(currentMoney * wholeDiscount));
                            }
                        }

                        @Override
                        public void onReset() {
                            wipedMoney = 0;
                            ViewBinder.setTextView(tv_wipe_zero,"");
                            ViewBinder.setTextView(tv_wipe_zero_num,"暂无");
                            SDToast.showToast(context,"无折扣");
                            float currentMoney = realMoney - wipedMoney;
                            wholeDiscount = 1;
                            ViewBinder.setTextView(tv_entire_discount,"");
                            ViewBinder.setTextView(tv_whole_discount,"暂无");
                            payMoney = currentMoney * wholeDiscount;
                            mustPayMoney = currentMoney * wholeDiscount;
                            ViewBinder.setTextView(tv_should_take_left,"¥"+(currentMoney * wholeDiscount));
                            ViewBinder.setTextView(tv_should_take_right,"¥"+(currentMoney * wholeDiscount));
                        }

                    }).setOutCancel(true).show(getChildFragmentManager());
                }else if(wipedMoney > 0){
                    SDToast.showToast(context,"抹零后不可打折");
                }
                KeyboardUtil.hideSoftInput(activity);
            }else{
                SDToast.showToast(context,"订单支付中");
            }
        }else if(id == R.id.rl_wipe_zero){//手动抹零
            if(ll_pay_results.getVisibility() == View.GONE){
                ManuallyWipeZeroDialog.newInstance(new ManuallyWipeZeroDialog.SetOnConfirmListener() {
                    @Override
                    public void onConfirm(Float wipeMoney) {
                        float currentMoney;
                        if(wholeDiscount > 0){
                            currentMoney = realMoney * wholeDiscount;
                        }else{
                            currentMoney = realMoney;
                        }
                        if(wipeMoney <= currentMoney){
                            wipedMoney = wipeMoney;
                            ViewBinder.setTextView(tv_wipe_zero,wipedMoney+"元");
                            ViewBinder.setTextView(tv_wipe_zero_num,wipedMoney+"元");
                            payMoney = currentMoney - wipeMoney;
                            mustPayMoney = currentMoney - wipeMoney;
                            ViewBinder.setTextView(tv_should_take_left,"¥"+(currentMoney - wipeMoney));
                            ViewBinder.setTextView(tv_should_take_right,"¥"+(currentMoney - wipeMoney));
                        }else{
                            SDToast.showToast(context,"抹去价格不可大于应付价格");
                        }
                    }

                    @Override
                    public void onReset() {
                        wipedMoney = 0;
                        float currentMoney;
                        if(wholeDiscount > 0){
                            currentMoney = realMoney * wholeDiscount;
                        }else{
                            currentMoney = realMoney;
                        }
                        ViewBinder.setTextView(tv_wipe_zero,"");
                        ViewBinder.setTextView(tv_wipe_zero_num,"暂无");
                        payMoney = currentMoney - wipedMoney;
                        mustPayMoney = currentMoney - wipedMoney;
                        ViewBinder.setTextView(tv_should_take_left,"¥"+(currentMoney - wipedMoney));
                        ViewBinder.setTextView(tv_should_take_right,"¥"+(currentMoney - wipedMoney));
                    }

                }).setOutCancel(true).show(getChildFragmentManager());
                KeyboardUtil.hideSoftInput(activity);
            }else{
                SDToast.showToast(context,"订单支付中");
            }
        }else if(id == R.id.rl_cash){
            payType = 1;
            payTypeChange();
        }else if(id == R.id.rl_wechat){
            payType = 2;
            payTypeChange();
        }else if(id == R.id.rl_alipay){
            payType = 3;
            payTypeChange();
        }else if(id == R.id.rl_yue){
            payType = 4;
            payTypeChange();
        }else if(id == R.id.rl_bank_card){
            payType = 5;
            payTypeChange();
        }else if(id == R.id.tv_0){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("0");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_00){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("00");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_1){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("1");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_2){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("2");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_3){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("3");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_4){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("4");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_5){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("5");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_6){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("6");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_7){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("7");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_8){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("8");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_9){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("9");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_10){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("10");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_20){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("20");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_50){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("50");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_100){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append("100");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_point){
            StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
            builder.append(".");
            ViewBinder.setTextView(tv_actual_take,builder.toString());
        }else if(id == R.id.tv_clear_actual){
            tv_actual_take.setText("");
        }else if(id == R.id.rl_del){
            if(tv_actual_take.getText().toString().length() > 0){
                StringBuilder builder = new StringBuilder(tv_actual_take.getText().toString());
                builder.deleteCharAt(tv_actual_take.getText().toString().length() - 1);
                ViewBinder.setTextView(tv_actual_take,builder.toString());
            }
        }else if(id == R.id.tv_confirm_order){
            if(payMoney > 0){
                if(payType == -1){
                    SDToast.showToast(context,"请选择支付方式");
                    return;
                }
                String actualTakeStr = tv_actual_take.getText().toString();
                if(TextUtils.isEmpty(actualTakeStr)){
                    SDToast.showToast(context,"请输入实收金额");
                    return;
                }
                if(!FormatUtil.isFloat(actualTakeStr)){
                    SDToast.showToast(context,"实收金额格式错误");
                    return;
                }
                Float actualPayMoney = Float.parseFloat(actualTakeStr);
                if(actualPayMoney >= payMoney){
                    SDToast.showToast(context,"订单已支付完成，找零"+(actualPayMoney - payMoney)+"元");
                    List<PayResultsModel> modelList = new ArrayList<>();
                    ll_pay_results.setVisibility(View.VISIBLE);
                    PayResultsModel payResultsModel = new PayResultsModel();
                    payResultsModel.setPayIndex(payType);
                    //payResultsModel.setPayMoney(actualPayMoney);
                    payResultsModel.setPayMoney(payMoney);
                    modelList.add(payResultsModel);
                    payResultsAdapter.addDatas(modelList);
                    completeOrder();
                    finishPay();
                }else{
                    payMoney = payMoney - actualPayMoney;
                    ViewBinder.setTextView(tv_should_take_left,"¥"+payMoney);
                    ViewBinder.setTextView(tv_should_take_right,"¥"+payMoney);
                    if(payMoney > 0){
                        SDToast.showToast(context,"部分付款成功,待付"+payMoney+"元");
                        ViewBinder.setTextView(tv_actual_take,"");
                    }
                    List<PayResultsModel> modelList = new ArrayList<>();
                    ll_pay_results.setVisibility(View.VISIBLE);
                    PayResultsModel payResultsModel = new PayResultsModel();
                    payResultsModel.setPayIndex(payType);
                    payResultsModel.setPayMoney(actualPayMoney);
                    modelList.add(payResultsModel);
                    payResultsAdapter.addDatas(modelList);
                }
            }else{
                SDToast.showToast(context,"订单已支付完成");
                finishPay();
                if(!goodList.isEmpty()){
                    goodList.clear();
                    adapter.setDatas(goodList);
                    refreshMoneyAndNum();
                }
            }
        }else if(id == R.id.btn_search_good_by_code){ //根据条码搜索商品
            String code = et_good_code.getText().toString();
            if(TextUtils.isEmpty(code)){
                SDToast.showToast(context,"请输入商品条形码");
                return;
            }
            SCommonInterface.getGoodInfoByCode(activity.getLocationId(), code, new AppRequestCallback<GoodInfoActModel>() {
                @Override
                protected void onSuccess(SDResponse sdResponse) {
                    if(actModel.isOk()){
                        GoodInfoActModel.GoodInfoByIdData data = actModel.getData();
                        if(data != null){
                            final GoodInfoActModel.GoodInfoByIdData.GoodInfoById goodInfoById = data.getRes();
                            if(goodInfoById != null){
                                GoodNumInputDialog.newInstance(GoodNumInputDialog.CHANGE_NUM,"",new GoodNumInputDialog.SetOnConfirmListener() {
                                    @Override
                                    public void onConfirm(String discount_result) {
                                        addGood(Float.parseFloat(discount_result),goodInfoById);
                                    }
                                }).setOutCancel(true).show(getChildFragmentManager());
                                KeyboardUtil.hideSoftInput(activity);
                            }else{
                                SDToast.showToast(context,"未查找到该商品");
                            }
                        }else{
                            SDToast.showToast(context,"未查找到该商品");
                        }
                    }else{
                        SDToast.showToast(context,"未查找到该商品");
                    }
                }
            });
        }else if(id == R.id.tv_return){
            if(ll_pay_results.getVisibility() == View.GONE){
                finishPay();
            }else{
                if(payMoney > 0){
                    CancelPaymentDialog.newInstance(new CancelPaymentDialog.SetOnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            SDToast.showToast(context,"取消支付");
                            finishPay();
                        }
                    }).setOutCancel(true).show(getChildFragmentManager());
                    KeyboardUtil.hideSoftInput(activity);
                }else{
                    SDToast.showToast(context,"订单已支付完成");
                    finishPay();
                }
            }
        }
    }

    //下单
    private void completeOrder(){
        String pay_types = "";
        String pay_prices = "";
        ArrayList<PayResultsModel> payresults = payResultsAdapter.getDatas();
        if(payresults != null && payresults.size() > 0){
            StringBuffer sb_type = new StringBuffer();
            StringBuffer sb_price = new StringBuffer();
            for(PayResultsModel payResultsModel: payresults){
                sb_type.append(payResultsModel.getPayType()).append(",");
                sb_price.append(payResultsModel.getPayMoney()).append(",");
            }
            pay_types = sb_type.deleteCharAt(sb_type.length() - 1).toString();
            pay_prices = sb_price.deleteCharAt(sb_price.length() - 1).toString();
        }

        String goodsId = "";
        String goodsNum = "";
        ArrayList<Good> goods = adapter.getDatas();
        if(goods != null && goods.size() > 0){
            StringBuffer sb_ids = new StringBuffer();
            StringBuffer sb_nums = new StringBuffer();
            for(Good good: goods){
                sb_ids.append(good.getId()).append(",");
                sb_nums.append(good.getNum()).append(",");
            }
            goodsId = sb_ids.deleteCharAt(sb_ids.length() - 1).toString();
            goodsNum = sb_nums.deleteCharAt(sb_nums.length() - 1).toString();
        }

        SCommonInterface.orderInsert(pay_types, pay_prices, mustPayMoney + "", goodsId,
                goodsNum, UserInfoModel.getUser_id(), new AppRequestCallback<BaseActModel>() {
                    @Override
                    protected void onSuccess(SDResponse sdResponse) {
                        LogUtil.e("orderInsert",sdResponse.getResult());
                    }

                    @Override
                    protected void onFinish(SDResponse resp) {
                        super.onFinish(resp);
                        payMoney = 0.0f;
                        mustPayMoney = 0.0f;
                        if(!goodList.isEmpty()){
                            goodList.clear();
                            adapter.setDatas(goodList);
                            refreshMoneyAndNum();
                        }
                    }
                });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        activity.unRegisterMyTouchListener(myTouchListener);
    }
}
